package com.explorex.infra.puma.gateway.netty.common.security;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import static javax.xml.bind.DatatypeConverter.parseHexBinary;

/**
 * @author: JacceYang
 * @createTime: 2022/09/07 11:13
 * @description:
 */
public class AESUtil {

    /**
     * AES加密算法
     *
     * @param key
     * @param input
     * @return
     * @throws GeneralSecurityException
     */
    public static byte[] encrypt(byte[] key, byte[] input) throws GeneralSecurityException {
        if (key == null || key.length == 0) {
            return input;
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return cipher.doFinal(input);
    }

    /**
     * AES 解密算法
     *
     * @param key
     * @param input
     * @return
     * @throws GeneralSecurityException
     */
    public static byte[] decrypt(byte[] key, byte[] input) throws GeneralSecurityException {
        if (key == null || key.length == 0) {
            return input;
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        return cipher.doFinal(input);
    }

    /**
     * @param passWord
     * @return
     */
    public static byte[] generateKey(String passWord) throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        if (StringUtils.isBlank(passWord)) {
            kg.init(128, new SecureRandom(passWord.getBytes()));
        } else {
            kg.init(128);
        }
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        byte[] bytes = generateKey("JacceYang");

        String string = "06485CFF96995C0CA8B43EF98FF5B6FD";

        byte[] bytes1 = parseHexBinary(string);
        System.out.println(bytes1);

    }
}
